﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using YmtAuth.Domain.Repository;
using YmtAuth.Domain.Shard;
using YmtAuth.Common;

namespace YmtAuth.Repository.MySQL
{
    public class AuthConfigurationRepository : MySQLRepository<AuthConfiguration>, IAuthConfigurationRepository
    {
        public AuthConfigurationRepository()
            : base(ConfigurationManager.AppSettings["AuthConfiguration_MySQLConnString"], "LoginSafeConfiguration")
        {
          
        }

        public IEnumerable<AuthConfiguration> TryFind(string appid)
        {
            var sql =
                "select `AppId`,`Code`,`Key`,`Value`,`CreateTime`,`LastUpdateTime` from LoginSafeConfiguration where `AppId`=@AppId";
            var par = this.Parameters.AddString("@AppId", appid).Build();
            return MySQLUtility.TryExecute(() =>
            {
                return Query(sql, par, ConfigUtility.LoginSafeSQLCommandTimeOut, CommandType.Text);
            });              
        }

        public IEnumerable<AuthConfiguration> TryFind(string appid, string code)
        {
            var sql =
                "select `AppId`,`Code`,`Key`,`Value`,`CreateTime`,`LastUpdateTime` from LoginSafeConfiguration where `AppId`=@AppId And `Code`=@Code";
            var par = this.Parameters.AddString("@AppId", appid).AddString("@Code", code).Build();
            return MySQLUtility.TryExecute(() =>
            {
                return Query(sql, par, ConfigUtility.LoginSafeSQLCommandTimeOut, CommandType.Text);
            });
        }

        public AuthConfiguration TryFind(string appid, string code, string key)
        {
            var sql =
                "select `AppId`,`Code`,`Key`,`Value`,`CreateTime`,`LastUpdateTime` from LoginSafeConfiguration where `AppId`=@AppId And `Code`=@Code AND `Key`=@Key";
            var par = this.Parameters.AddString("@AppId", appid).AddString("@Code", code).AddString("@Key", key).Build();
            return MySQLUtility.TryExecute(() =>
            {
                return Query(sql, par, ConfigUtility.LoginSafeSQLCommandTimeOut, CommandType.Text).SingleOrDefault();
            });
        }
    }
}
